import { useState } from 'react';
import api from '../http/index'
import { message } from 'antd/lib';

const useAuth = () => {
    const [token, setAccessToken] = useState(null);
    const [refreshToken, setRefreshToken] = useState(null);

    const login = async ({account, password}) => {
        const res = await api.UserApi.login({ account, password })
        if(res && res.code ===200){
            message.success('登录成功')
            setAccessToken(res.data.token);
            localStorage.setItem('token', res.data.token)
            setRefreshToken(res.data.refreshToken);
            localStorage.setItem('refreshToken', res.data.refreshToken)
            window.location.replace('/#/')
            return
        }
        message.error(res?.msg)
    };

    const logout = () => {
        setAccessToken(null);
        setRefreshToken(null);
        localStorage.clear()
    };


    return [ login, logout, token, refreshToken ];
};

export default useAuth;
